<template>
  <div class="page-content" :style="{height:minHeight}">
    <div class="left-group">
      <el-button @click="showTypeDialog('add')">添加分类</el-button>
      <div class="warp">
        <ul>
          <li class="item" :class="type_id === item.id ? 'ac' : ''" v-for="item in typeData" :key="item.id" @click="chooseType(item)">
            <span>{{item.name}}</span>
            <div>
              <el-button size="small" text plain @click="showTypeDialog('edit',item)">编辑</el-button>
              <el-button size="small" text plain @click="delType(item)">删除</el-button>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div class="right-container" style="height: 100%">
      <table-bar
        :showTop="false"
        @search="search"
        @reset="resetForm(searchFormRef)"
        layout="search, refresh"
      >
      <template #bottom>
        <el-button @click="showTagDialog('add')" v-ripple>绑定账号</el-button>
      </template>
      </table-bar>
      <art-table style="margin-top: 0" :data="tagData" show-header-background>
        <template #default>
          <el-table-column label="名称" prop="name" />
          <el-table-column label="备注" prop="remark" />
          <el-table-column label="创建日期" prop="create_time" sortable />
          <el-table-column fixed="right" label="操作" width="150px">
            <template #default="scope">
              <button-table type="edit" @click="showTagDialog('edit', scope.row)" />
              <button-table type="delete" @click="deleteTag(scope.row)" />
            </template>
          </el-table-column>
        </template>
      </art-table>
    </div>
    <!--  添加分类-->
    <el-dialog v-model="dialogTypeVisible" :title="dialogType === 'add' ? '添加分类' : '编辑分类'" width="30%">
      <el-form ref="formRefType" :model="formType" :rules="rulesType" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formType.name" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input type="number" v-model="formType.sort"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogTypeVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmitType">提 交</el-button>
        </div>
      </template>
    </el-dialog>
    <!--  添加标签  -->
    <el-dialog v-model="dialogVisible" :title="dialogTag === 'add' ? '添加标签' : '编辑标签'" width="30%">
      <el-form ref="formRefTag" :model="formTag" :rules="rulesTag" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formTag.name" />
        </el-form-item>
        <el-form-item label="分类" prop="type_id">
          <el-select v-model="formTag.type_id">
            <el-option v-for="item in typeData" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input type="number" v-model="formTag.sort"/>
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input type="textarea" v-model="formTag.remark" :rows="3"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmitTag">提 交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ElMessageBox, ElMessage } from 'element-plus'
  import type { FormRules,FormInstance } from 'element-plus'
  import { useSettingStore } from '@/store/modules/setting'
  import { TagService } from '@/api/customer/tagApi'

  const settingStore = useSettingStore()
  const showWorkTab = computed(() => settingStore.showWorkTab)
  const minHeight = computed(() => `calc(100vh - ${showWorkTab.value ? 120 : 75}px)`)

  // 分类参数
  const formType = reactive({
    id: '',
    name: '',
    sort: '1'
  })

  // 添加标签参数
  const formTag = reactive({
    name: '',
    remark: '',
    id:'',
    type_id: '',
    sort: ''
  })

  // 分类dialog
  const dialogTypeVisible = ref(false)
  const dialogType = ref('add')

  // 添加dialog
  const dialogVisible = ref(false)
  const dialogTag = ref('add')

  const typeData = ref()
  const tagData = ref([])
  
  // 分类id
  const type_id = ref(0)

  const rulesType = reactive<FormRules>({
    name: [
      { required: true, message: '请输入', trigger: 'blur' },
    ]
  })

  const rulesTag = reactive<FormRules>({
    name: [
      { required: true, message: '请输入', trigger: 'blur' },
    ],
    type_id: [
      { required: true, message: '请选择分类', trigger: 'blur' },
    ],
  })

  getTypePage().then(() => {
    getTagPage()
  })

  // 获取分类列表
  async function getTypePage() {
    const res = await TagService.getTypeList()
    typeData.value = res.data
    formTag.type_id = res.data[0].id
    console.log('formTag', formTag)
    type_id.value = res.data[0].id
  }
  
  // 获取标签列表
  async function getTagPage() {
    const res = await TagService.getTagList({type_id:type_id.value})
    tagData.value = res.data
  }

  const searchFormRef = ref<FormInstance>()

  const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
  }
  
  // 选择分类
  const chooseType = (row:any)=> {
    type_id.value = row.id
    formTag.type_id = row.id
    getTagPage()
  }
  // 删除分类
  const delType = (row:any)=> {
    ElMessageBox.confirm('确定要删除该分类吗？', '系统提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(async () => {
      await TagService.typeDelete({id:row.id})
      await getTypePage()
      await getTagPage()
      ElMessage.success('删除成功')
    })
  }
  
  // 添加分类dialog
  const showTypeDialog = (type: string, row?: any)=> {
    dialogTypeVisible.value = true
    dialogType.value = type

    if (type === 'edit' && row) {
      formType.id = row.id
      formType.name = row.name
      formType.sort = row.sort
    } else {
      formType.id = ''
      formType.name = ''
      formType.sort = '1'
    }
  }
  
  // 添加标签dialog
  const showTagDialog = (type: string, row?: any) => {
    dialogVisible.value = true
    dialogTag.value = type

    if (type === 'edit' && row) {
      formTag.name = row.name
      formTag.remark = row.remark
      formTag.id = row.id
      formTag.type_id = row.type_id
      formTag.sort = row.sort

    } else {
      formTag.name = ''
      formTag.remark = ''
      formTag.type_id = ''
      formTag.sort = '1'
    }
  }

  // 删除标签
  const deleteTag = (row:any) => {
    ElMessageBox.confirm('确定要删除该标签吗？', '系统提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(async () => {
      await TagService.tagDelete({id:row.id})
      await getTagPage()
      ElMessage.success('删除成功')
    })
  }

  const search = () => {}

  const formRefType = ref<FormInstance>()
  const formRefTag = ref<FormInstance>()
  
  const handleSubmitType = async () => {
    if (!formRefType.value) return
    await formRefType.value.validate(async(valid) => {
      if (valid) {
        if(dialogType.value === 'add') {
          await TagService.typeCreate(toRaw(formType))
        } else {
          await TagService.typeUpdate(toRaw(formType))
        }
        await getTypePage()
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
        dialogTypeVisible.value = false
      }
    })
  }
  
  const handleSubmitTag = async () => {
    if (!formRefTag.value) return
    await formRefTag.value.validate(async (valid) => {
      if (valid) {
        if (dialogTag.value === 'add') {
          await TagService.tagCreate(toRaw(formTag))
        } else {
          await TagService.tagUpdate(toRaw(formTag))
        }
        await getTagPage()
        ElMessage.success(dialogTag.value === 'add' ? '添加成功' : '更新成功')
        dialogVisible.value = false
      }
    })
  }
</script>

<style lang="scss" scoped>
  .page-content {
    width: 100%;
    display: flex;
    .left-group {
      width: 20%;
      .warp {
        height: calc(100% - 40px);
        overflow-y: scroll;
        margin-top: 20px;
        .item {
          cursor: pointer;
          font-size: 14px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          .el-button {
            margin: 0;
            padding: 5px;
          }
        }
        .ac {
          background: #F6F6F6;
        }
        li {
          padding: 6px 16px;
          margin-bottom: 4px;
        }
      }
    }
    .right-container {
      width: 80%;
      margin-left: 4px;
    }
  }
</style>
